package com.example.administrator.ksf_zty.Activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;

import com.example.administrator.ksf_zty.JavaModels.SysUserModel;
import com.example.administrator.ksf_zty.R;
import com.example.administrator.ksf_zty.util.BaseActivity;
import com.example.administrator.ksf_zty.util.Config;
import com.example.administrator.ksf_zty.util.HttpUtil;
import com.example.administrator.ksf_zty.util.SQLiteHelper;
import com.example.administrator.ksf_zty.util.Tips;
import com.example.administrator.ksf_zty.util.TitleUtils;
import com.example.administrator.ksf_zty.util.Update;
import com.google.gson.Gson;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.example.administrator.ksf_zty.util.Common.checkUpdate;
import static com.example.administrator.ksf_zty.util.HttpUtils.StrHttp_URLGetLogin_UserList;

public class UserLoginActivity extends BaseActivity {

    private static SQLiteDatabase sqLiteDatabase;
    EditText txtI_WERKS;
    EditText txtCode;
    EditText txtName;
    EditText txtPWD;
    private Handler handler;
    private RelativeLayout load;
    ImageButton back;
    Button titleButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_login);

        SetTitle();

        txtI_WERKS = (EditText) findViewById(R.id.UserLogin_txtI_WERKS);
        txtCode = (EditText) findViewById(R.id.UserLogin_txtCode);
        txtName = (EditText) findViewById(R.id.UserLogin_txtName);
        txtPWD = (EditText) findViewById(R.id.UserLogin_txtPWD);


        load = (RelativeLayout) findViewById(R.id.load);

        //实例化handler接收子线程的更新消息
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                new Update(UserLoginActivity.this, msg.obj.toString()).checkUpdateInfo();//执行更新
            }
        };

        //创建数据库
        SQLiteHelper.createSQLite(UserLoginActivity.this);

        SQLiteOpenHelper helper = new SQLiteHelper(UserLoginActivity.this, Config.DataBaseName, null, 1);
        sqLiteDatabase = helper.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("select IP,Port,I_WERKS from SysSet ", null);
        if (cursor.moveToFirst()) {
            txtI_WERKS.setText(cursor.getString(cursor.getColumnIndex("I_WERKS")));
            Log.d("TS", cursor.getString(cursor.getColumnIndex("I_WERKS")));
        }


        //登录按钮
        Button UserLogin_btnLogin = (Button) findViewById(R.id.UserLogin_btnLogin);
        UserLogin_btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //测试页面跳转
                Intent intent = new Intent(UserLoginActivity.this, MainActivity.class);
                intent.putExtra("name", "");//传参数
                startActivity(intent);

                //登录条码调整
                //Login();
            }
        });

        //设置Web
        Button UserLogin_btnSysSet = (Button) findViewById(R.id.UserLogin_btnSysSet);
        UserLogin_btnSysSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserLoginActivity.this, SysSetActivity.class);
                intent.putExtra("name", "");//传参数
                startActivity(intent);
            }
        });

        //取消按钮
        Button UserLogin_btnCalCen = (Button) findViewById(R.id.UserLogin_btnCalCen);
        UserLogin_btnCalCen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.exit(0);
            }
        });

    }

    //登录验证
    private void Login() {
        final String strI_Werks = txtI_WERKS.getText().toString();
        final String strUserCode = txtCode.getText().toString();
        final String strPWD = txtPWD.getText().toString();

        if (strI_Werks.isEmpty()) {
            //工厂不能为空
            Tips.show(UserLoginActivity.this, "工号不能为空", 1000);
            return;
        }
        if (strUserCode.isEmpty()) {
            //用户名不能为空
            Tips.show(UserLoginActivity.this, "用户名不能为空", 1000);
            return;
        }
        if (strPWD.isEmpty()) {
            //密码不能为空
            Tips.show(UserLoginActivity.this, "密码不能为空", 1000);
            return;
        }
        //***************************在线模式登录Begion******************
        //判断用户名、密码是否正确  远程判断
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("I_WERKS", strI_Werks);
        builder.add("userCode", strUserCode);
        RequestBody formBody = builder.build();
        HttpUtil.sendOkHttpRequest(StrHttp_URLGetLogin_UserList, formBody, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("LOG111", "网络异常11");
                UserLoginActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //这里的代码在主线程中执行
                        Tips.show(UserLoginActivity.this, "网络异常11", 1000);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("LOG111", "成功");
                //解析数据
                final String responseData = response.body().string();
                try {
                    final JSONObject obj = new JSONObject(responseData);
                    if (obj.getString("success").equals("0")) {
                        //给集合对象里面赋值
                        SysUserModel sysUserModel = new Gson().fromJson(responseData, SysUserModel.class);
                        final String strhttpPassWord = sysUserModel.getList().get(0).getPassWord();
                        //判断密码是否正确
                        if (strPWD.equals(strhttpPassWord)) {
                            //密码正确页面跳转
                            Intent intent = new Intent(UserLoginActivity.this, MainActivity.class);
                            intent.putExtra("name", "");//传参数
                            startActivity(intent);

                        } else {
                            //弹出提示框
                            UserLoginActivity.this.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    //这里的代码在主线程中执行
                                    Tips.show(UserLoginActivity.this, "密码错误", 1000);
                                }
                            });
                        }
                        //密码错误提示错误
                        //                                //循环获取集合里面的数据
                        //                                for (int i = 0;i<sysUserModel.getList().size();i++)
                        //                                {
                        //                                    sysUserModel.getList().get(i).getI_WERKS();
                        //                                    sysUserModel.getList().get(i).getName();
                        //                                    sysUserModel.getList().get(i).getPassWord();
                        //                                }
                    } else {
                        //弹出提示框
                        UserLoginActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //这里的代码在主线程中执行
                                Tips.show(UserLoginActivity.this, "用户不存在", 1000);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //********************在线模式登录End****************************


        //***************************系统断开模式登录Begion******************


        //***************************系统断开模式登录End******************


    }

    @Override
    protected void onResume() {
        super.onResume();
        checkUpdate(UserLoginActivity.this, handler, load, false);//检查更新
    }

    //设置Title
    private void SetTitle() {
        back = (ImageButton) findViewById(R.id.back);
        titleButton = (Button) findViewById(R.id.titleButton);
        //设置标题(第三个参数是标题文字，直接替换""内容即可，第五个参数是标题右边按钮文字，第六个参数是设置是否显示返回按钮)
        TitleUtils.setTitle(this, R.id.title_sys_set, "登录页面(Ver1.0.1)", this,
                "", false);
        //返回按钮事件
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

    }
}
